<template>
  <div>
    <el-dialog
      :title="fileDialogTitle"
      :visible.sync="fileDialogVisible"
      width="98%"
      top="20px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      append-to-body
    >
      <el-form ref="filePostForm" :model="filePostForm" class="form-container" label-width="200px" :rules="fjrules">
        <el-form-item label="文件" prop="file">
          <el-upload
            class="upload-demo"
            :action="this.$http.defaults.baseURL+'api/gen/file/upload/'"
            :on-success="handleUploadSucc"
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            :on-error="uploadError"
            :multiple="false"
            :file-list="fileList"
            :headers="myHeaders"
            :limit="1"
            :on-exceed="handleExceed"
          >
            <el-button type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="分类" prop="classCode">
          <el-select v-model="filePostForm.classCode" placeholder="请选择" clearable style="width: 200px" class="filter-item">
            <el-option v-for="(it,index) in typeList" :key="index" :label="it.label" :value="it.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="说明" prop="remark">
          <el-input v-model="filePostForm.remark" type="textarea" style="width:800px" rows="10" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="loading" @click="submitFileForm">保存</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <h3>附件</h3>
    <el-table
      ref="processTable"
      v-loading="fjloading"
      :data="fjList"
      border
      fit
      highlight-current-row
      style="width: 100%;margin-bottom:20px;"
    >
      <el-table-column key="name" prop="name" label="文件名" width="600" align="left">

        <template slot-scope="scope">
          <el-tooltip v-if="scope.row.fileType==='png'||scope.row.fileType==='jpg'||scope.row.fileType==='jpeg'||scope.row.fileType==='pdf'||scope.row.fileType==='gif'" placement="top" content="在线预览">
            <el-button icon="el-icon-search" type="text" @click="viewFile(scope.row)" />
          </el-tooltip>
          {{ scope.row.name }}
        </template>
      </el-table-column>
      <el-table-column key="classCodeText" prop="classCodeText" label="类型" width="160" align="center" />
      <el-table-column key="dataCreateDatetime" prop="dataCreateDatetime" label="上传时间" width="160" align="center" />
      <el-table-column key="remark" prop="remark" label="说明" min-width="400" align="left" show-overflow-tooltip />
      <el-table-column
        v-if="readOnly"
        key="btnsReadOnly"
        width="400"
      >
        <template
          slot="header"
        >操作
        </template>
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.fileType==='png'||scope.row.fileType==='jpg'||scope.row.fileType==='jpeg'||scope.row.fileType==='pdf'||scope.row.fileType==='gif'"
            type="success"
            @click="viewFile(scope.row)"
          >查看</el-button>
          <el-button
            @click="download(scope.row)"
          >下载</el-button>
        </template>
      </el-table-column>
      <el-table-column
        v-if="!readOnly"
        key="btns"
        width="400"
      >
        <template
          slot="header"
        >
          <el-button
            key="addbtn"
            type="success"
            @click="addFile"
          >新增</el-button>
        </template>
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.fileType==='png'||scope.row.fileType==='jpg'||scope.row.fileType==='jpeg'||scope.row.fileType==='pdf'||scope.row.fileType==='gif'"
            type="success"
            @click="viewFile(scope.row)"
          >查看</el-button>
          <el-button
            @click="download(scope.row)"
          >下载</el-button>
          <el-button
            type="primary"
            @click="editFile(scope.$index,scope.row)"
          >修改</el-button>
          <el-popconfirm
            title="确定删除该信息吗？"
            style="margin-left:10px;"
            @onConfirm="handleDeleteFile(scope.$index)"
          >
            <el-button slot="reference" type="danger">删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
const defaultFileForm = {
  fileid: 0,
  classCode: '',
  remark: ''
}
export default {
  name: 'ArticleDetail',
  props: {
    readOnly: {
      type: Boolean,
      default: false
    },
    timestamp: {
      type: Number,
      default: 0
    },
    id: {
      type: Number,
      default: 0
    },
    table: {
      type: String,
      default: ''
    }
  },
  data() {
    const validateRequire = (rule, value, callback) => {
      if (value === '') {
        // this.$message({
        //   message: '请将表单填写完整',
        //   type: 'error'
        // })
        callback(new Error('必填项'))
      } else {
        callback()
      }
    }
    return {
      typeList: [],
      fjloading: false,
      fjindex: -1,
      fileList: [],
      fjList: [],
      fileDialogVisible: false,
      fileDialogTitle: '新增',
      myHeaders: {},
      filePostForm: Object.assign({}, defaultFileForm),
      loading: false,
      fileTypeOption: [],
      fjrules: {
        classCode: [{ validator: validateRequire }]
      }
    }
  },
  watch: {
    readOnly: {
      deep: true,
      handler: (newVal, oldVal) => {
        this.readOnly = newVal
      }
    },
    timestamp: {
      handler(val, oldVal) {
        console.log(val)
        this.fjList = []
        if (this.id && this.id !== '') {
          this.getFj()
        }
      },
      immediate: true
    },
    fjList: {
      handler(val, oldVal) {
        this.$emit('updateFj', val)
      },
      immediate: true
    }
  },
  mounted() {
    this.myHeaders = {
      Authorization: 'Bearer ' + localStorage.getItem('token')
    }
    this.getOptions()
  },
  methods: {
    download(item) {
      window.open(this.$http.defaults.baseURL + 'api/gen/file/download?download=true&id=' + item.id)
    },
    viewFile(item) {
      window.open(this.$http.defaults.baseURL + 'api/gen/file/download?id=' + item.id)
    },
    handleExceed(files, fileList) {
      this.$message.warning(`一次最多只能上传一个文件`)
    },
    uploadError(err) {
      console.log(err)
      this.$message({
        message: '上传失败:' + err,
        type: 'error',
        duration: 10000
      })
    },
    handleUploadSucc(response, file, fileList) {
      if (response.success) {
        this.$message({
          type: 'success',
          message: '上传成功!'
        })
        this.fileList.push({ id: response.result[0].id, name: response.result[0].fileName + '.' + response.result[0].fileType, fileType: response.result[0].fileType, url: this.$http.defaults.baseURL + 'api/gen/file/download?id=' + response.result[0].id, dataCreateDatetime: response.result[0].dataCreateDatetime })
      } else {
        this.$message({
          message: '上传失败:' + response.message,
          type: 'error',
          duration: 10000
        })
      }
    },
    dateFormat(date) {
      console.log('日期转换')
      console.log(date)
      return date.getFullYear().toString() + '-' + (date.getMonth() + 1).toString() + '-' + date.getDate().toString()
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    handleRemove(file, fileList) {
      console.log(file, fileList)
      const fid = file.id
      this.$http.get('api/gen/file/remove?id=' + fid).then(res => {
        if (res.data.success === true) {
          this.fileList = this.fileList.filter(item => item.id !== fid)
          this.$message({
            message: '删除成功！',
            type: 'success'
          })
        }
      })
    },
    handleDeleteFile(index) {
      this.fjList.splice(index, 1)
    },
    submitFileForm() {
      if (this.fileList && this.fileList.length > 0) {
        this.$refs.filePostForm.validate(valid => {
          if (valid) {
            console.log(this.fileList)
            this.fileList[0].remark = this.filePostForm.remark
            this.fileList[0].classCode = this.filePostForm.classCode
            this.fileList[0].classCodeText = this.typeList.find(item => item.value === this.filePostForm.classCode).label
            this.filePostForm = Object.assign({}, defaultFileForm)
            if (this.fjindex === -1) {
              this.fjList.push(this.fileList[0])
            } else {
              this.fjList[this.fjindex] = this.fileList[0]
              this.fjindex = -1
            }
            this.fileList = []
            this.fileDialogVisible = false
          } else {
            console.log('error submit!!')
            return false
          }
        })
      } else {
        this.$message({
          message: '请上传文件',
          type: 'error'
        })
      }
    },
    editFile(index, item) {
      this.fileList = []
      this.fileList.push(item)
      this.filePostForm.remark = item.remark
      this.filePostForm.classCode = item.classCode
      this.filePostForm.dataCreateDatetime = item.dataCreateDatetime
      this.fjindex = index
      this.fileDialogVisible = true
      this.fileDialogTitle = '修改'
    },
    addFile() {
      this.filePostFormForm = Object.assign({}, defaultFileForm)
      this.fileDialogVisible = true
      this.fileDialogTitle = '新增'
    },
    getFj() {
      this.fjloading = true
      this.$http
        .get('/api/gen/file/searchById?businessTable=' + this.table + '&businessId=' + this.id)
        .then(response => {
          this.fjloading = false
          if (response.data.success === true) {
            this.fjList = response.data.result.map(item => { return { name: item.fileName + '.' + item.fileType, remark: item.remark, id: item.id, dataCreateDatetime: item.dataCreateDatetime, classCodeText: item.classCodeText, classCode: item.classCode, fileType: item.fileType } })
          } else {
            console.log('获取失败:' + response.data.message)
            this.$message({
              message: '获取失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(function(error) {
          console.log(error)
          this.fjloading = false
        })
    },
    getOptions() {
      this.$http
        .get('/api/sysDict/getByCode?enabled=true&code=04')
        .then(response => {
          if (response.data.success === true) {
            this.typeList = response.data.result
          } else {
            console.log('获取失败:' + response.data.message)
            this.$message({
              message: '获取失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
        })
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
